1 Using typedefs for legibility
typedef int testScore_t;
testScore_t GradeTest();
2 Using typedefs for easier code maintenance
Typedefs also allow you to change the underlying type of an object without having to change lots of code. For example, if you were using a short to hold a student’s ID number, but then later decided you needed a long instead, you’d have to comb through lots of code and replace short with long. It would probably be difficult to figure out which shorts were being used to hold ID numbers and which were being used for other purposes.
However, with a typedef, all you have to do is change typedef short studentID_t to typedef long studentID_t. However, precaution is necessary when changing the type of a typedef to a type in a different type family (e.g. an integer to a floating point value, or vice versa)! The new type may have comparison or integer/floating point division issues that the old type did not.
3 Platform independent coding
#ifdef INT_2_BYTES
typedef char int8_t;
typedef int int16_t;
typedef long int32_t;
#else
typedef char int8_t;
typedef short int16_t;
typedef int int32_t;
#endif
4 Using typedefs to make complex types simple
typedef std::vector
pairlist_t pairlist; // instantiate a pairlist_t
bool hasDuplicates(pairlist_t pairlist) // use pairlist_t in a function parameter
{
// some code here
}
5 Type aliases in C++11
Typedefs have a few issues. First, it’s easy to forget whether the type name or type definition come first. Which is correct?
typedef distance_t double; // incorrect
typedef double distance_t; // correct
I can never remember.
Second, the syntax for typedefs gets ugly with more complex types (as we’ll explore further in the section on function pointers).
To help address these issues, in C++11, a new, improved syntax for typedefs has been introduced that mimics the way variables are declared. This syntax is called a type alias. A type alias introduces a name that can be used as a synonym for a type.
Given the following typedef:
typedef double distance_t; // define distance_t as an alias for type double
In C++11, this can be declared as:
using distance_t = double; // define distance_t as an alias for type double
The two are functionally equivalent.
本页共38段,2595个字符,2641 Byte(字节)